package com.ptkc.web.filter;

import com.ptkc.utils.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: Mr.Jiao
 * @date: 2018年11月21日
 */
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "iPFilter")
public class IPFilter implements Filter {

    @Value("${spring.license}")
    private String license;

    private Set<String> licenseArrays = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        licenseArrays = new HashSet<>();
        if(StringUtil.isNotEmpty(this.license)){
            licenseArrays.addAll(Arrays.asList(license.split(",")));
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(licenseArrays.size() > 0) {
            HttpServletRequest servletRequest = (HttpServletRequest) request;
            String ip = this.getIp(servletRequest);
            if(licenseArrays.contains(ip)){
                chain.doFilter(request, response);
            }
        }else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }

    public String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
}
